﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using OgilvyOne.IDAL;

namespace OgilvyOne.SqlServerDAL
{
    /// <summary>
    /// 文章收藏
    /// </summary>
    public class ArticleCollection : IArticleCollection
    {
        private const string ADD_SQL = "insert into COFCO_ARTICLE_COLLECTION(MEMBER_ID,ARTICLE_ID,ADD_TIME) values(@MEMBER_ID,@ARTICLE_ID,getDate()) ";
        //收藏
        public bool Add(int aid, int memberid)
        {
            if (!IsExitis(aid, memberid))
            {
                SqlParameter[] parms = new SqlParameter[] { 
                
                new SqlParameter("@MEMBER_ID",SqlDbType.Int,4),
                
                new SqlParameter("@ARTICLE_ID", SqlDbType.Int, 4)
            };

                parms[0].Value = memberid;
                parms[1].Value = aid;


                int i = SQLHelper.ExecuteSql(ADD_SQL, parms);
                if (i > 0) return true;
                return false;
            }
            return true;
        }

        private const string IS_EXITIS_SQL = "select ARTICLE_ID from COFCO_ARTICLE_COLLECTION where MEMBER_ID=@MEMBER_ID and ARTICLE_ID=@ARTICLE_ID";
        //是否已收藏
        public bool IsExitis(int aid, int memberid)
        {
            SqlParameter[] parms = new SqlParameter[] { 
                
                new SqlParameter("@MEMBER_ID",SqlDbType.Int,4),
                
                new SqlParameter("@ARTICLE_ID", SqlDbType.Int, 4)
            };

            parms[0].Value = memberid;
            parms[1].Value = aid;
            bool re = false;
            using (SqlDataReader rdr = SQLHelper.ExecuteReader(SQLHelper.CONN_STRING_NON_DTC, CommandType.Text, IS_EXITIS_SQL, parms))
            {
                if (rdr.Read())
                {
                    re = true;
                }
            }
            return re;
        }

        public DataSet GetCollectionList(int aid, int memberid)
        {
            string querysql = "select cmi.MEMBER_NICKNAME,ca.TITLE,cac.* from COFCO_ARTICLE_COLLECTION cac, COFCO_MEMBER_INFO cmi, CMS_ARTICLE ca where cac.MEMBER_ID=cmi.MEMBER_ID and cac.ARTICLE_ID=ca.ARTICLEID";
            if (aid > 0)
            {
                querysql += " and cac.ARTICLE_ID=" + aid;
            }
            if (memberid > 0)
            {
                querysql += " and cac.MEMBER_ID=" + memberid;
            }
            querysql += " order by cac.ADD_TIME desc";
            
            return SQLHelper.Query(querysql);
        }

        public bool Delete(int cid)
        {
            int i = SQLHelper.ExecuteSql("delete from COFCO_ARTICLE_COLLECTION where COLLECTION_ID=" + cid, new SqlParameter[] { });
            if (i > 0) return true;
            return false;
        }
    }
}
